import React, { useRef, useEffect, useState } from 'react';
import './style/index';
/**
 * 组件参数
 */

/**
 * 三级类目
 * @export
 * @interface ThirdItem
 */
interface ThirdItem {
  firstLetter: string;
  id: number;
  title: string;
}
interface IProps {
  list: Array<Item>;
  onclick: (id: number) => void;
  containerHeight?: string | number;
}

interface Item {
  label: string;
  content: Array<ThirdItem>;
}

const IndexBar = ({ list, onclick, containerHeight = '100vh' }: IProps) => {
  const ref = useRef<HTMLInputElement>(null);
  const indexListRef = useRef<HTMLInputElement>(null);
  const [touching, setTouching] = useState<boolean>(false);
  const [boxHeight, setBoxHeight] = useState<number>(0);
  const [boxClientTop, setBoxClientTop] = useState<number>(0);
  const [ch, setCh] = useState<string>(() => list[0]?.label);
  const [indexListHeight, setIndexListHeight] = useState<number[]>([]);
  const [touchEnd, setTouchEnd] = useState<boolean>(true);
  const height = 21 * list?.length;

  /** 跳转指定索引位置 */
  const goToChar = (chs: string) => {
    // 添加手机振动反馈
    const { navigator } = window;
    const vibrate =
      navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate;
    if (vibrate && touchEnd) {
      try {
        vibrate(10);
      } catch (error) {
        console.log('设备不支持振动')
      }
    }

    setCh(chs);
    const index = list.findIndex(el => el.label === chs);
    const item: any = ref?.current;
    // 获取对应char
    const target: any = ref?.current?.querySelector(`[data-ch="${chs}"]`);
    if (target) {
      item.scrollTop = indexListHeight[index];
      // item.scrollTop = target.offsetTop
      // target.scrollIntoView()
    }
  };

  /** 获取手指位置在组件内部相对高度 */
  const calcRelativePosition = (clientY: number) => {
    let y = clientY - boxClientTop;
    if (y < 0) {
      y = 0;
    } else if (y > boxHeight) {
      y = boxHeight;
    }
    return y;
  };

  /** 获取当前chars */
  const getPositionChar = (yPercent: any) => {
    const min = 1;
    const max = list?.length;
    let index = Math.ceil(yPercent * max);
    if (index < min) {
      index = min;
    } else if (index > max) {
      index = max;
    }
    return list[index - 1]?.label;
  };

  const move = (clientX: number, clientY: number) => {
    // 手指在组件内相对高度
    const offset = calcRelativePosition(clientY);
    // 手指相对高度与组件高度的比列
    const percent = offset / boxHeight;
    const chs = getPositionChar(percent);
    goToChar(chs);
  };

  const getIndexOffsetTop = () => {
    const tempHeight: number[] = [];
    list?.forEach((el: any, index: number) => {
      const chartItem: any = ref?.current?.querySelector(`[data-ch="${el.label}"]`);
      if (chartItem) {
        const h = chartItem?.offsetTop;
        tempHeight.push(h);
      }
    });
    setIndexListHeight(tempHeight);
  };

  const handleTouchStart = (e: any) => {
    if (!touching) {
      // e.preventDefault()
      setTouchEnd(true);
      const t = e.touches[0];
      setTouching(true);
      move(t.clientX, t.clientY);
    }
  };

  const handleTouchMove = (e: any) => {
    if (touching) {
      // e.preventDefault()
      setTouchEnd(true);
      const t = e.touches[0];
      move(t.clientX, t.clientY);
    }
  };

  const handleTouchEnd = (e: any) => {
    setTouchEnd(false);
  };

  /**
   * 监听索引栏滚动事件
   * @param e
   */
  const onscroll = (e: any) => {
    setTouchEnd(false);
    const t = e.target.scrollTop;
    for (let index = 0; index < indexListHeight.length; index++) {
      const el = indexListHeight[index];
      if (t >= el && t < indexListHeight[index + 1]) {
        const chs = list[index]?.label;
        setCh(chs);
      }
    }
  };

  useEffect(() => {
    // 初始化更新当前页面滚动条
    ref?.current?.scrollTo(0, 0);
    setCh('');
    // 获取A-Z盒子高度
    const boxRect = indexListRef?.current?.getBoundingClientRect();
    setBoxHeight(height || 0);
    setBoxClientTop(boxRect?.top || 0);
    // 获取A-Z对应内容 offsetTop
    getIndexOffsetTop();
  }, [list]);

  return (
    <div className="index-bar-container" style={{ maxHeight: containerHeight }} ref={ref}>
      <div className="index-content-list" onScroll={onscroll}>
        {list?.map((item: Item, index: number) => (
          // <StickyContainer>
          <div key={index} data-ch={item.label} data-label="ch">
            <div className="title">{item.label}</div>
            {/* <Sticky topOffset={80}>
                {({ style }) => (
                  <div className="title" style={{ ...style }}>
                    {item.label}
                  </div>
                )}
              </Sticky> */}
            <div className="items-card">
              {/* style={{ ...style, 'left': '24px' }} */}

              <div className="list">
                {item?.content?.map((i: ThirdItem, j: number) => (
                  <div className="item" key={j} onClick={() => onclick(i.id)}>
                    {i.title}
                  </div>
                ))}
              </div>
            </div>
          </div>
          // </StickyContainer>
        ))}
      </div>
      <div
        className="indexBar"
        onTouchStart={handleTouchStart}
        onTouchMove={handleTouchMove}
        onTouchEnd={handleTouchEnd}
        ref={indexListRef}
        style={{ height: `${height}px` }}
      >
        <ul>
          {list?.map((item: Item, index: number) => (
            <li
              key={index}
              className={`${ch === item.label && 'active'}`}
              onClick={() => goToChar(item.label)}
            >
              {item.label}
              {ch === item.label && touchEnd && <span className="active-pop">{item.label}</span>}
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
};

export default IndexBar;
